package com.bailan.foreat.service.impl;

import com.bailan.foreat.entity.Product;
import com.bailan.foreat.es.ESDataWriter;
import com.bailan.foreat.es.ESProductRepository;
import com.bailan.foreat.mapper.ProductMapper;
import com.bailan.foreat.mapper.ProductTypeMapper;
import com.bailan.foreat.service.ProductService;
import com.bailan.foreat.vo.EsProduct;
import com.bailan.foreat.vo.ProductVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ste
 * @since 2023-02-21 07:50:43
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ESProductRepository esProductRepository;

    @Autowired
    ProductTypeMapper productTypeMapper;

    @Autowired
    @Qualifier("esProduct")
    ESDataWriter esDataWriter;


    //旧版，更换为下方select
    /*@Override
    public Page<EsProduct> searchByES(Integer currentPage, Integer pageSize, String keyword, Integer storeId) {
        //es查询

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //query
        nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(keyword, "productName"));
        nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(storeId, "storeId"));

        //分页条件
        //注意: es中的分页是从第0页开始的
        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage - 1, pageSize));

        //排序
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("buyCount").order(SortOrder.DESC));

        org.springframework.data.domain.Page<EsProduct> esBookPage = esProductRepository.search(nativeSearchQueryBuilder.build());

        //将 Es的page 转换 mybatisPlus的 page
        Page<EsProduct> productPage = new Page<>(currentPage, pageSize);
        productPage.setPages(esBookPage.getTotalPages());
        productPage.setTotal(esBookPage.getTotalElements());
        productPage.setRecords(esBookPage.getContent());

        return productPage;
    }*/

    @Override
    public Page<EsProduct> searchByES(Integer currentPage, Integer pageSize, String keyword, Integer typeIdKeyword,Integer storeId) {

        //判断es是否有数据,如果没有数据就写入
        if (!esProductRepository.findAll().iterator().hasNext())
            esDataWriter.dataWrite();
        //es查询

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //商店
        if (null != storeId &&  storeId  > 0 ){
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("storeId", storeId);
            boolQueryBuilder.must(termQueryBuilder);
        }
        //字段模糊
            if (null != keyword && !"".equals(keyword)){
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("productName", keyword);
            boolQueryBuilder.must(matchQueryBuilder);
        }
        //种类精确
        if (null != typeIdKeyword && typeIdKeyword > 0 ){
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("typeIds", typeIdKeyword);
            boolQueryBuilder.must(termQueryBuilder);
        }
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

        //分页条件
        //注意: es中的分页是从第0页开始的
        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage - 1, pageSize));

        //排序
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("buyCount").order(SortOrder.DESC));

        org.springframework.data.domain.Page<EsProduct> esBookPage = esProductRepository.search(nativeSearchQueryBuilder.build());

        //将 Es的page 转换 mybatisPlus的 page
        Page<EsProduct> productPage = new Page<>(currentPage, pageSize);
        productPage.setPages(esBookPage.getTotalPages());
        productPage.setTotal(esBookPage.getTotalElements());
        productPage.setRecords(esBookPage.getContent());
        return productPage;
    }

    @Override
    public Page selectAll(Integer currentPage, Integer pageSize, Integer storeId) {
        Page page = new Page<>(currentPage, pageSize);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id", storeId);
        Page<Product> productPage = productMapper.selectPage(page, wrapper);
        Page productPage2 = productPage;
        List<ProductVo> productVoList = new ArrayList<>();
        for (Product record : productPage.getRecords()) {
            ProductVo productVo = new ProductVo();
            productVo.setId(record.getId());
            productVo.setProductName(record.getProductName());
            productVo.setProductPrice(record.getProductPrice());
            productVo.setProductImg(record.getProductImg());
            productVo.setType(record.getType());
            productVo.setBuyCount(record.getBuyCount());
            productVo.setStockCount(record.getStockCount());
            productVo.setStatus(record.getStatus());
            productVo.setStoreId(record.getStoreId());
            productVo.setTypeName(productTypeMapper.selectById(record.getType()).getTypeName());
            productVoList.add(productVo);
        }
        productPage2.setRecords(productVoList);
        return productPage2;
    }

    @Override
    public Product selectById(Integer id) {
        Product product = productMapper.selectById(id);
        return product;
    }
}
